package com.ghsc.ghxc.jsb.ui.home.activity

import android.content.Context
import android.content.pm.ActivityInfo
import android.graphics.Paint
import android.text.TextUtils
import android.view.View
import android.webkit.JavascriptInterface
import android.webkit.WebSettings
import android.widget.EditText
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.allen.library.shape.ShapeTextView
import com.blankj.utilcode.util.NetworkUtils
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.cn.appcore.base.BaseVMActivity
import com.cn.appcore.ext.afterTextChangeListener
import com.cn.appcore.ext.dp
import com.cn.appcore.ext.encodeToStr
import com.cn.appcore.ext.load
import com.cn.appcore.ext.loge
import com.cn.appcore.ext.showToast
import com.cn.appcore.ext.startKtxActivity
import com.cn.appcore.ext.transformRoundCorner
import com.cn.appcore.utils.GlideEngine
import com.cn.appcore.utils.GlideUtil
import com.cn.appcore.utils.GsonUtil
import com.ghsc.ghxc.jsb.R
import com.ghsc.ghxc.jsb.api.ApiMarket
import com.ghsc.ghxc.jsb.config.CustKey
import com.ghsc.ghxc.jsb.config.LoginHelper
import com.ghsc.ghxc.jsb.databinding.ActivityCommodityDetailBinding
import com.ghsc.ghxc.jsb.ext.http.request
import com.ghsc.ghxc.jsb.ext.intentExtras
import com.ghsc.ghxc.jsb.ext.setOnFastClickListener
import com.ghsc.ghxc.jsb.ext.showCustomPopup
import com.ghsc.ghxc.jsb.ext.textString
import com.ghsc.ghxc.jsb.ui.home.adapter.CommodityDetailBannerAdapter
import com.ghsc.ghxc.jsb.ui.home.bean.CommodityDetailBean
import com.ghsc.ghxc.jsb.ui.home.bean.GetSkuBean
import com.ghsc.ghxc.jsb.ui.home.bean.SkuBean
import com.ghsc.ghxc.jsb.ui.home.bean.SkuItemBean
import com.ghsc.ghxc.jsb.ui.home.bean.SkuItemSelectBean
import com.google.gson.Gson
import com.library.flowlayout.FlowLayoutManager
import com.library.flowlayout.SpaceItemDecoration
import com.luck.picture.lib.PictureSelector
import com.luck.picture.lib.config.PictureMimeType
import com.luck.picture.lib.entity.LocalMedia
import com.lxj.xpopup.core.BottomPopupView
import com.lxj.xpopup.util.KeyboardUtils
import com.youth.banner.indicator.CircleIndicator
import java.net.URLEncoder
import java.nio.charset.StandardCharsets

/**
 * 项目：GuoHuaJsb
 * 包名：com.ghsc.ghxc.jsb.ui.home.activity
 * 类名：GoodsDetailActivity
 * 创建时间：2024/4/24 14:55
 * 创建人 @author： xiaolin
 * 描述 ：Todo...商品详情
 */
class GoodsDetailActivity : BaseVMActivity<GoodsDetailVIewModel, ActivityCommodityDetailBinding>() {
    override fun attachLayoutRes(): Int {
        return R.layout.activity_commodity_detail
    }

    override fun attachVMClass(): Class<GoodsDetailVIewModel>? {
       return GoodsDetailVIewModel::class.java
    }


    private val pid: String? by intentExtras("pid", "0")
    override fun initImmersionBar() {
        super.initImmersionBar()
        mImmersionBar!!.statusBarDarkFont(true).init()
    }
    override fun initView() {
    }



    private var commodityDetailBean: CommodityDetailBean? = null
    private var skuBean: SkuBean? = null

    override fun initData() {
        super.initData()
        val map: HashMap<String, Any> = HashMap()
        map["pid"] = pid.toString()
        GsonUtil.mapToJsonStrObjEncryption(map)?.let { it1 -> mViewModel.commodityDetail(it1) }
    }


    override fun initClickListener() {
        super.initClickListener()
        binding.apply {
            tvCommoditySpecification.setOnFastClickListener {
                //商品规格
                val map: HashMap<String, Any> = HashMap()
                map["pid"] = pid.toString()
                GsonUtil.mapToJsonStrObjEncryption(map)?.let { it1 -> mViewModel.skuItem(it1) }
            }
            rlClose.setOnFastClickListener {
                finish()
            }
            sllBuy.setOnFastClickListener {
                val map: HashMap<String, Any> = HashMap()
                map["pid"] = pid.toString()
                GsonUtil.mapToJsonStrObjEncryption(map)?.let { it1 -> mViewModel.skuItem(it1) }
            }
            tvShare.setOnFastClickListener {
//                showToast("即将上线,敬请期待")

            }
        }
    }


    override fun initRequestObserver() {
        super.initRequestObserver()
        mViewModel.apply {
            errorMsg.observe(this@GoodsDetailActivity) {
                showToast(it)
            }
            againLoginMsg.observe(this@GoodsDetailActivity) {
                showToast(CustKey.IN_AGAIN_MSG)
                LoginHelper.startLoginPage()
            }
            commodityDetailResult.observe(this@GoodsDetailActivity) {
                //详情
                it.data.let {
                    commodityDetailBean = it
                    val bannerList = it.images.split(",")
                    if (bannerList.isNotEmpty()) {
                        it.img = bannerList[0]
                    }
                    //设置banner
                    binding.banner.setAdapter(CommodityDetailBannerAdapter(bannerList))
                        .addBannerLifecycleObserver(this@GoodsDetailActivity)
                        .indicator = CircleIndicator(this@GoodsDetailActivity)


                    binding.tvCommodityName.text = it.title
                    binding.tvPrice.text=it.price.toString() //价格
                    binding.tvOriprice.text="￥ "+it.oriprice.toString() //原价
                    binding.tvOriprice.paint.flags = Paint.STRIKE_THRU_TEXT_FLAG
                    binding.tvSalecnt.text="销量:  "+it.salecnt.toString()

                    val webSettings: WebSettings = binding.webView.settings
                    webSettings.javaScriptEnabled = true //允许使用js
                    webSettings.setSupportZoom(false)
                    webSettings.builtInZoomControls = false
                    webSettings.displayZoomControls = false
                    binding.webView.addJavascriptInterface(AndroidInterface(),"android")
                    binding.webView.loadData(it.detail, "text/html", "UTF-8")

                    if (it.resstock <= 0) {
                        binding.sllBuy.visibility=View.GONE
                        binding.clSellOut.visibility=View.VISIBLE
                    }else{
                        binding.sllBuy.visibility=View.VISIBLE
                        binding.clSellOut.visibility=View.GONE
                    }

                }
            }
            skuItemResult.observe(this@GoodsDetailActivity) {
                it.data.let {
                    val skuList = mutableListOf<SkuItemBean>()
                    it.data.forEach { mapItem ->
                        val skuItemSelectList = mutableListOf<SkuItemSelectBean>()
                        val selectList = mapItem.value as MutableList<String>
                        selectList.forEachIndexed { index, s ->
                            skuItemSelectList.add(SkuItemSelectBean(mapItem.key!! as String, s, false))
                        }
                        val bean = SkuItemBean(mapItem.key as String?, skuItemSelectList)
                        skuList.add(bean)
                    }
                    commodityDetailBean?.run {
                        if (skuBean == null) {
                            skuBean = SkuBean(pid, title, price, img, resstock, skuList)
                        } else {
                            skuBean?.isSelected = true
                        }
                        val commoditySpecificationPopup =
                            CommoditySpecificationPopup(this@GoodsDetailActivity, skuBean!!)
                        commoditySpecificationPopup.apply {
                            showCustomPopup(this, builder = {
                                autoFocusEditText(false)
                            })
                        }
                        commoditySpecificationPopup.setSelectResultCallback(object :
                            SelectResultCallback {
                            override fun selectResult(bean: SkuBean) {
                                skuBean = bean
                                val stringBuilder = StringBuilder()
                                bean.data.forEach {
                                    it.list?.forEach {
                                        if (it.isSelected) {
                                            stringBuilder.append("${it.name} ")
                                        }
                                    }
                                }
                                binding.tvCommoditySpecification.text = " $stringBuilder"
                            }
                        })
                        commoditySpecificationPopup.setBuyResultCallback(object :
                            BuyResultCallback {
                            override fun buyResult(skuId: String, count: Int) {
                                this@GoodsDetailActivity.startKtxActivity<SubmitOrderActivity>(
                                    values = arrayListOf(
                                        "pid" to pid,
                                        "skuId" to skuId,
                                        "count" to "$count",
                                        )
                                )
                            }
                        })
                    }
                }
            }
        }
    }

    var selectList: MutableList<LocalMedia> = ArrayList()
    inner class AndroidInterface {
        @JavascriptInterface
        fun zoomImage(urls:String,index:Int) {
            // 处理图片放大的逻辑
            if (selectList.size>0){
                // 预览图片 可自定长按保存路径
                PictureSelector.create(this@GoodsDetailActivity)
                    .themeStyle(R.style.picture_default_style) // xml设置主题
                    //.setPictureWindowAnimationStyle(animationStyle)// 自定义页面启动动画
                    .setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED) // 设置相册Activity方向，不设置默认使用系统
                    .isNotPreviewDownload(true) // 预览图片长按是否可以下载
                    //.bindCustomPlayVideoCallback(new MyVideoSelectedPlayCallback(getContext()))// 自定义播放回调控制，用户可以使用自己的视频播放界面
                    .imageEngine(GlideEngine.createGlideEngine()) // 外部传入图片加载引擎，必传项
                    .openExternalPreview(index, selectList)
            }else{

                val imageUrls: List<String> = urls.split(",")
                for( i in imageUrls.indices){
                    val localMedia = LocalMedia()
                    localMedia.path = imageUrls[i]
                    localMedia.mimeType= PictureMimeType.MIME_TYPE_IMAGE
                    selectList.add(localMedia)
                }
                // 预览图片 可自定长按保存路径
                PictureSelector.create(this@GoodsDetailActivity)
                    .themeStyle(R.style.picture_default_style) // xml设置主题
                    //.setPictureWindowAnimationStyle(animationStyle)// 自定义页面启动动画
                    .setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED) // 设置相册Activity方向，不设置默认使用系统
                    .isNotPreviewDownload(true) // 预览图片长按是否可以下载
                    //.bindCustomPlayVideoCallback(new MyVideoSelectedPlayCallback(getContext()))// 自定义播放回调控制，用户可以使用自己的视频播放界面
                    .imageEngine(GlideEngine.createGlideEngine()) // 外部传入图片加载引擎，必传项
                    .openExternalPreview(index, selectList)

            }

        }

    }





    inner class CommoditySpecificationPopup(context: Context, bean: SkuBean) : BottomPopupView(context) {

        private val mContext = context
        private var buyCount = 1
        private var skuid = "-1"
        private lateinit var etCount: EditText
        private val data = bean
        private var tvSelect: TextView? = null
        private var tvCommodityName: TextView? = null
        private var tvRealPrice: TextView? = null
        private var tvIntegral: TextView?= null
        private var tvInventory: TextView? = null
        private var ivCommodityImg: ImageView? = null
        private var stvBuy: ShapeTextView? = null
        //        private var sllBuy: ShapeLinearLayout? = null
        private var callback: SelectResultCallback? = null
        private var buyCallback: BuyResultCallback? = null

        override fun getImplLayoutId() = R.layout.popup_commodity_specification


        var isBug =true


        override fun onCreate() {
            super.onCreate()
            val ivAdd = findViewById<ImageView>(R.id.ivAdd)
            val rvSpecification = findViewById<RecyclerView>(R.id.rvSpecification)
            ivCommodityImg = findViewById(R.id.ivCommodityImg)
            tvCommodityName = findViewById(R.id.tvCommodityName)
            tvRealPrice = findViewById(R.id.tvRealPrice)
            tvIntegral = findViewById(R.id.tvIntegral)
            tvInventory = findViewById(R.id.tvInventory)
            tvSelect = findViewById(R.id.tvSelect)
            stvBuy = findViewById(R.id.stvBuy)
            if(commodityDetailBean!=null){
                if (commodityDetailBean!!.resstock <= 0) {
                    isBug=false
                    stvBuy!!.text=binding.tvSellOut.text.toString().trim()
                }else{
                    isBug=true
                    stvBuy!!.text="立即购买"
                }
            }
            val tvRMB = findViewById<TextView>(R.id.tvRMB)
            val ivDelete = findViewById<ImageView>(R.id.ivDelete)
            etCount = findViewById(R.id.etCount)
            val commoditySpecificationAdapter = CommoditySpecificationAdapter()
            rvSpecification.adapter = commoditySpecificationAdapter
            rvSpecification.layoutManager = LinearLayoutManager(mContext)
            if (!data.isSelected){
                for (i in data.data.indices){
                    if(data.data[i].list!=null)
                        if (data.data[i].list!!.size>0) {
                            data.data[i].list!![0].isSelected=true
                            data.isSelected=true
                        }
                }
            }
            commoditySpecificationAdapter.setNewInstance(data.data)
            if (data.isSelected) {
                val skuMap = hashMapOf<String, Any>()
                data.data.forEach {
                    it.list?.forEach {
                        if (it.isSelected) {
                            skuMap[it.type] = it.name
                        }
                    }
                }
                loadSkuInfo(skuMap)
            } else {
                tvInventory?.text = "剩余 ${data.resstock} 件"

            }
            tvCommodityName?.text = data.name
            tvRealPrice?.text = "${data.price}"
            ivCommodityImg?.load(data.image, builder = {
                transform(transformRoundCorner(10))
            })
            buyCount = etCount.textString.trim().toInt()
            ivDelete.setOnClickListener {
                if (buyCount <= 1) return@setOnClickListener
                buyCount--
                etCount.setText("$buyCount")
                KeyboardUtils.hideSoftInput(this)
            }
            ivAdd.setOnClickListener {
                if (buyCount >= 99) return@setOnClickListener
                buyCount++
                etCount.setText("$buyCount")
                KeyboardUtils.hideSoftInput(this)
            }
            etCount.afterTextChangeListener {
                if (it.isNotEmpty()) {
                    buyCount = it.toInt()
                    ivDelete.isEnabled = it.toInt() > 1
                    ivAdd.isEnabled = it.toInt() <= data.resstock
                }
            }
            stvBuy?.setOnFastClickListener {
                if(isBug){
                    if (skuid == "-1") {
                        showToast("请选择规格")
                        return@setOnFastClickListener
                    }
                    buyCallback?.buyResult(skuid, buyCount)
                    delayDismiss(500)
                }else{
                    showToast( stvBuy!!.text.toString().trim())
                }

            }
        }

        override fun onKeyboardHeightChange(height: Int) {
            super.onKeyboardHeightChange(height)
            if (height == 0) {
                val result = etCount.textString
                if (result.isEmpty() || result.toInt() < 1) {
                    buyCount = 1
                    etCount.setText("$buyCount")
                }
            }
        }

        inner class CommoditySpecificationAdapter :
            BaseQuickAdapter<SkuItemBean, BaseViewHolder>(R.layout.layout_commodity_specification_item) {


            override fun convert(holder: BaseViewHolder, item: SkuItemBean) {
                holder.setText(R.id.tvTitle, item.type)
                val rvSkuItem = holder.getView<RecyclerView>(R.id.rvSkuItem)
                rvSkuItem.addItemDecoration(SpaceItemDecoration(5.dp))
                rvSkuItem.layoutManager = FlowLayoutManager()
                val commoditySpecificationFlowAdapter = CommoditySpecificationFlowAdapter()
                commoditySpecificationFlowAdapter.setNewInstance(item.list)
                rvSkuItem.adapter = commoditySpecificationFlowAdapter
                commoditySpecificationFlowAdapter.setOnItemClickListener { adapter, view, position ->
                    val bean = commoditySpecificationFlowAdapter.data
                    bean.forEach {
                        it.isSelected = false
                    }
                    bean[position].isSelected = true
                    val skuMap = hashMapOf<String, Any>()
                    data.forEach {
                        it.list?.forEach {
                            if (it.isSelected) {
                                skuMap[it.type] = it.name
                            }
                        }
                    }
                    loadSkuInfo(skuMap)
                    callback?.selectResult(this@CommoditySpecificationPopup.data)
                    commoditySpecificationFlowAdapter.notifyDataSetChanged()
                }
            }
        }

        inner class CommoditySpecificationFlowAdapter :
            BaseQuickAdapter<SkuItemSelectBean, BaseViewHolder>(R.layout.layout_commodity_specification_flow_item) {

            override fun convert(holder: BaseViewHolder, item: SkuItemSelectBean) {
                val tvTag = holder.getView<TextView>(R.id.tvTag)
                tvTag.text = item.name
                tvTag.isSelected = item.isSelected
            }
        }

        private fun loadSkuInfo(skuMap: HashMap<String, Any>) {
            if (!NetworkUtils.isConnected()) {
                showToast("没有网络了~")
                return
            }

            loge("规格====="+GsonUtil.mapToJsonStrObj(skuMap)!!)

            val encodedUrl =
                URLEncoder.encode(GsonUtil.mapToJsonStrObj(skuMap)!!, StandardCharsets.UTF_8.toString())
                    .replace("\\+".toRegex(), "%20")
            val base64String =encodedUrl.encodeToStr()
            val map = hashMapOf<String, Any>()
            map["pid"] = this@CommoditySpecificationPopup.data.id
            map["skuvalue"] = base64String
            GsonUtil.mapToJsonStrObjEncryption(map)?.let { it1 ->
                request({ ApiMarket.service.getSku(it1) }, { data ->
                    updateData(data)
                })
            }
        }

        fun updateData(getSkuBean: GetSkuBean) {
            getSkuBean.run {
                if (price != null && resstock != null && skuvalue != null && images != null && skuid != null) {
                    tvRealPrice?.text = "$price"
                    if (pay_jifen>0){
                        tvIntegral?.text= "积分$pay_jifen"
                    }else{
                        tvIntegral?.text=""
                    }
                    tvInventory?.text = "剩余 $resstock 件"
                    tvSelect?.text = "已选 $skuvalue"
                    GlideUtil.ImageLoad(ivCommodityImg?.context, images, ivCommodityImg)
                    this@CommoditySpecificationPopup.skuid = skuid
                }
            }
        }

        fun setSelectResultCallback(callback: SelectResultCallback) {
            this.callback = callback
        }

        fun setBuyResultCallback(callback: BuyResultCallback) {
            this.buyCallback = callback
        }


    }

    interface SelectResultCallback {
        fun selectResult(bean: SkuBean)
    }

    interface BuyResultCallback {
        fun buyResult(skuId: String, count: Int)
    }

}